package com.example.demo.tool.archery;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;


/**
 * @author jiangjinwu
 * @since 2025/10/24 16:55
 * @version 1.0
 */

@Slf4j
@Service
public class ArcheryQueryService {

    public JSONObject execute(QueryContext queryContext) {

        StringBuilder sb = new StringBuilder();
        sb.append( queryContext.getSelContent());
        if (queryContext.getDynamicCondition() != null){
            sb.append(queryContext.getDynamicCondition());
        }
        String limit = "limit " + queryContext.getPageIndex() * queryContext.getPageSize() + "," + queryContext.getPageSize();
        sb.append("  ").append(limit);
        String sql =sb.toString();
        logger.info("sql:{}",sql);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
        RequestBody body = RequestBody.create(mediaType,
                "instance_name="+queryContext.getInstanceName()+"&db_name="+queryContext.getDbName()+"&schema_name=&tb_name=t_relation_event&sql_content="
                        +sql + "&limit_num=0");
        Request request = new Request.Builder()
                .url(queryContext.getUrl().getValue())
                .method("POST", body)
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
                .addHeader("Connection", "keep-alive")
                .addHeader("Origin", queryContext.getUrl().getHost())
                .addHeader("Referer", queryContext.getUrl().getHost()+"/sqlquery/")
                .addHeader("User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
                .addHeader("X-CSRFToken",queryContext.getCsrfToken())
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",queryContext.getCookie())
                .addHeader("Authorization", "Bearer {{token}}")
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONUtil.parseObj(response.body().string());
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
